package com.hst.capacity.application.biz.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.smartravel.framework.redis.domain.LiveLocation;
import com.alibaba.fastjson2.JSON;
import com.hst.capacity.application.biz.DriverBiz;
import com.hst.capacity.application.biz.MiniProgramBiz;
import com.hst.capacity.domain.common.constants.Constants;
import com.hst.capacity.domain.exception.BusinessException;
import com.hst.capacity.domain.model.entity.driver.DriverAccountEntity;
import com.hst.capacity.domain.model.entity.driver.DriverEntity;
import com.hst.capacity.domain.model.entity.driver.DriverProfileEntity;
import com.hst.capacity.domain.model.entity.order.intercity.IntercityOrderEntity;
import com.hst.capacity.domain.model.request.driver.*;
import com.hst.capacity.domain.model.response.PagingResultVO;
import com.hst.capacity.domain.model.response.driver.DriverBandCarVO;
import com.hst.capacity.domain.model.response.driver.DriverPagingVO;
import com.hst.capacity.domain.model.response.driver.OrderPoolDriverPagingVO;
import com.hst.capacity.domain.service.DriverService;
import com.hst.capacity.domain.service.UploadService;
import com.hst.capacity.domain.service.VehicleService;
import com.hst.capacity.infra.convertor.DriverConvertor;
import com.hst.capacity.infra.persistence.jpa.driver.DriverAccountRepository;
import com.hst.capacity.infra.persistence.jpa.driver.DriverProfileRepository;
import com.hst.capacity.infra.persistence.jpa.driver.DriverRepository;
import com.hst.capacity.infra.persistence.jpa.order.intercity.IcOrderRepository;
import com.hst.capacity.infra.persistence.mybatis.DriverMapper;
import com.hst.capacity.infra.util.FileUtil;

import com.qiniu.storage.model.DefaultPutRet;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class DriverBizImpl implements DriverBiz {

    @Autowired
    private DriverService driverService;
    @Autowired
    private DriverRepository driverRepository;
    @Autowired
    private DriverProfileRepository driverProfileRepository;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private VehicleService vehicleService;
    @Autowired
    private DriverAccountRepository accountRepository;
    @Autowired
    private MiniProgramBiz miniProgramBiz;
    @Autowired
    private IcOrderRepository icOrderRepository;

    /**
     * 分页并条件查询司机信息
     * @param param
     * @return
     */
    @Override
    public PagingResultVO<DriverPagingVO> search(DriverSearchParam param) {
        if (param.getLineFlg()==1){
            IntercityOrderEntity order = icOrderRepository.findByIdOrder(param.getIdOrder());
            if (order!=null && !StringUtil.isNullOrEmpty(order.getIdLine())){
                param.setIdLine(order.getIdLine());
            }
        }
        PagingResultVO<DriverPagingVO> resultVO = new PagingResultVO<>(driverMapper.searchWithConditionsAndPagingTotal(param) ,driverMapper.searchWithConditionsAndPaging(param));
        return resultVO;
    }

    @Override
    public PagingResultVO<DriverPagingVO> stpSearch(DriverSearchParam param) {
        PagingResultVO<DriverPagingVO> resultVO = new PagingResultVO<>(driverMapper.stpDriverSearchPagingTotal(param) ,driverMapper.stpDriverSearchPaging(param));
        return resultVO;
    }

    @Override
    public PagingResultVO<DriverPagingVO> cityLineSearch(DriverSearchParam param) {
        PagingResultVO<DriverPagingVO> resultVO = new PagingResultVO<>(driverMapper.cityLineDriverSearchPagingTotal(param) ,driverMapper.cityLineDriverSearchPaging(param));
        return resultVO;
    }

    @Override
    public PagingResultVO<OrderPoolDriverPagingVO> orderPoolSearch(DriverSearchParam param) {
        PagingResultVO<OrderPoolDriverPagingVO> resultVO = new PagingResultVO<>(driverMapper.orderPoolDriverSearchPagingTotal(param) ,driverMapper.orderPoolDriverSearchPaging(param));
        return resultVO;
    }

    /**
     * 司机绑定车辆
     * @param param
     * @return
     */
    @Override
    public DriverBandCarVO driverBandVehicle(DriverBandCarParam param) {
//        return DriverConvertor.INSTANCE.convertBandCarVo(driverService.driverBandVehicle(param));
        return driverService.driverBandVehicle(param);
    }

    @Override
    public String deviceUnband(String idDriver) {
        return driverService.deviceUnband(idDriver);
    }

    @Override
    public LiveLocation driverLocation(String idDriver) {
        return driverService.driverLocation(idDriver);
    }

    /**
     * 创建司机信息
     * @param param
     * @return
     */
    @Override
    public String add(DriverAddParam param, MultipartFile[] multipartFiles) {
        // 图片已上传只需要保存图片路径
//        uploadService.save(multipartFiles, param);
        DriverEntity driver = driverService.save(param);

        if (StringUtil.isNullOrEmpty(param.getQrcode())){
            String qrCode = createFileDriverQrCode(driver.getIdDriver());
            driverProfileRepository.updateQrcode(qrCode, driver.getIdDriverProfile());
        }

        return driver.getIdDriver();
    }

    /**
     * 获取司机绑定车辆信息
     * @param idDriver
     * @return
     */
    @Override
    public DriverBandCarVO driverListVehicle(String idDriver) {
//        return DriverConvertor.INSTANCE.convertBandCarVo(driverEntityByIdDriver);
        return driverService.findDriverEntityByIdDriver(idDriver);
    }

    /**
     * 司机添加资质
     * @param param
     * @return
     */
    @Override
    public Object driverAddCertificate(DriverAddCertificateParam param) {
        return driverService.driverAddCertificate(param);
    }

    /**
     * 司机解绑绑车辆
     * @param param
     * @return
     */
    @Override
    public Boolean driverUnBandVehicle(DriverUnBandCarParam param) {
        return driverRepository.unBandVehicle(param.getIdDriver())==1;
    }

    @Override
    public Boolean review(String idDriver) {
        boolean result = (driverRepository.driverUpdateStatus(Constants.DriverStatus.OFFLINE, idDriver) == 1);
        return result;
    }

    /**
     * 更新司机状态
     * @param status
     * @param idDriver
     * @return
     */
    @Override
    public Boolean driverUpdateStatus(Integer status, String idDriver) {
        boolean result = driverRepository.driverUpdateStatus(status, idDriver) == 1;
        if (result){
            // TODO 价格更改记录

        }
        return result;
    }

    /**
     * 编辑查询司机
     * @param idDriver
     * @return
     */
    @Override
    public Object driverEditSelect(String idDriver,String moduleName) {
        DriverEntity driver = driverRepository.findByIdDriver(idDriver);
        Object re;
        if (driver==null)
            throw new BusinessException(5002,"司机ID不存在请检查");
        if (moduleName.equals("driver")){
            DriverProfileEntity driverProfile = driverProfileRepository.findByIdDriverProfile(driver.getIdDriverProfile());
            re=DriverConvertor.INSTANCE.convert(driver,driverProfile);
        }else if (moduleName.equals("vehicle")){
            if (StrUtil.isEmpty(driver.getIdVehicle()))
                return null;
            re=vehicleService.vehicleEditSelectBase(driver.getIdVehicle());
        }else if (moduleName.equals("driverCar")){
            re=ListUtil.toList(driverListVehicle(idDriver));
        }else if (moduleName.equals("driverDeposit")){
            re=driverSaveAccountSelect(idDriver);
        }else if (moduleName.equals("driverCertificate")){
            re=driverService.driverAddCertificateSelect(idDriver);
        }else {
            throw new BusinessException(5002,"moduleName["+moduleName+"]不存在请检查");
        }
        return re;
    }

    /**
     * 查询指定司机信息
     * @param idDriver
     * @return
     */
    @Override
    public HashMap getDriverInfoByDriverId(String idDriver) {
        HashMap<String, Object> returns = new HashMap<>();
        DriverEntity driver = driverRepository.findByIdDriver(idDriver);
        DriverProfileEntity driverProfile = driverProfileRepository.findByIdDriverProfile(driver.getIdDriverProfile());
        returns.put("driver",DriverConvertor.INSTANCE.convert(driver,driverProfile));
        returns.put("vehicle",vehicleService.vehicleEditSelectBase(driver.getIdVehicle()));
        returns.put("driverCar", ListUtil.toList(driverListVehicle(idDriver)));
        return returns;
    }

    @Override
    public String driverSaveAccount(SaveAccountParam param) {
        DriverAccountEntity driverAccountEntity;
        String idWithdrawDepositAccount = null;
        if (StrUtil.isNotEmpty(param.getIdWithdrawDepositAccount())){
            driverAccountEntity=accountRepository.findById(param.getIdWithdrawDepositAccount()).orElse(null);
            if (driverAccountEntity==null)
                throw new BusinessException(4003,"账号ID[idWithdrawDepositAccount]不存在");
            DriverConvertor.INSTANCE.convert(driverAccountEntity,param);
        }else {
            driverAccountEntity=newDriverAccountEntity(param);

            idWithdrawDepositAccount = accountRepository.save(driverAccountEntity).getIdWithdrawDepositAccount();
        }

        return idWithdrawDepositAccount;
    }

    @Override
    public SaveAccountParam driverSaveAccountSelect(String idDriver) {
        DriverAccountEntity find;
        try {
            find= accountRepository.findByIdOwnerAndIdAccount(idDriver, idDriver);
        }catch (Exception e){
            throw new BusinessException(4003,"数据库数据重复,请检查");
        }
        return DriverConvertor.INSTANCE.convert(find);
    }

    @Override
    public Boolean driverStatusToggle(String idDriver) {
        Integer status=0;
        DriverEntity driverEntity = driverRepository.findById(idDriver).get();
        if (driverEntity.getStatus() == Constants.DriverStatus.FREEZE)status=Constants.DriverStatus.OFFLINE;
        if (driverEntity.getStatus() != Constants.DriverStatus.FREEZE)status=Constants.DriverStatus.FREEZE;
        driverMapper.updateStatus(idDriver,status);
        return status==Constants.DriverStatus.OFFLINE;
    }

    @Override
    public List driverAssociateVehicle(String idFranchisee,String str) {
        return vehicleService.driverAssociateVehicle(idFranchisee,str);
    }

    @Override
    public int fleetDriverCount(String idFleet) {
        return driverRepository.fleetDriverCount(idFleet);
    }

    private DriverAccountEntity newDriverAccountEntity(SaveAccountParam param){
        DriverAccountEntity driverAccountEntity = new DriverAccountEntity();
//        driverAccountEntity.setIdWithdrawDepositAccount(param.getIdWithdrawDepositAccount());
        driverAccountEntity.setIdOwner(param.getIdOwner());
        driverAccountEntity.setIdAccount(param.getIdOwner());
        driverAccountEntity.setCategory(param.getCategory());
        driverAccountEntity.setWithdrawDepositOrganization(param.getWithdrawDepositOrganization());
        driverAccountEntity.setWithdrawDepositAccount(param.getWithdrawDepositAccount());
        driverAccountEntity.setWithdrawDepositUserName(param.getWithdrawDepositUserName());
        driverAccountEntity.setWithdrawDepositIdCard("");
        driverAccountEntity.setWithdrawDepositPassword("");
        driverAccountEntity.setMobile("");
//        driverAccountEntity.setStatus();
        driverAccountEntity.setInUse(0);
//        driverAccountEntity.setMemo();
//        driverAccountEntity.setCreateBy();
//        driverAccountEntity.setCreateTime();
        return driverAccountEntity;
    }

    @Override
    public String createDriverQrCode(String idDriver) {

        byte[] qrCode = miniProgramBiz.createDriverQrCode(idDriver);
        //司机二维码保存路径
        String subPath = Constants.Image_Path_Type.get(7);
        //String newFileName = new Date().getTime() + ".png";
        String newFileName = subPath + "/" + idDriver + ".png";

        //String localPath = "/opt/smartravel/temp/";
        String localPath = "/opt/smartravel/driver/qrcode/";
        String fileName = idDriver + ".png";
        FileUtil.bytesToFile(qrCode,localPath,fileName);
        File file = new File(localPath + fileName);
        DefaultPutRet updRet = uploadService.uploadImageByFile(newFileName,file);
       // DefaultPutRet updRet = uploadService.uploadImageByBytes(newFileName, qrCode);

        return updRet.key;
    }

    @Override
    public String createFileDriverQrCode(String idDriver) {

        File qrCode = miniProgramBiz.createFileDriverQrCode(idDriver);
        String fileName = "/opt/smartravel/driver/qrcode/" + idDriver + ".png";
        //String fileName = "D:/opt/" + idDriver + ".jpg";
        File newFile = new File(fileName);
        qrCode.renameTo(newFile);
        //司机二维码保存路径
        String subPath = Constants.Image_Path_Type.get(7);
        String newFileName = subPath + "/" + idDriver + ".png";

        DefaultPutRet updRet = uploadService.uploadImageByFile(newFileName, newFile);
        return updRet.key;

    }

}
